package com.ruoyi.web.controller.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Export2ExcelListMap {

    public static void export(HttpServletResponse response,List<String> headNames,
                       List<Map<String,Object>> dataList,
                       String...params
                       ) throws IOException {

        //表头 如果需要改动表头样式与实体类方法一致
        List<List<String>> heads = new ArrayList<>();

        for (String head:headNames) {
            heads.add(Arrays.asList(head));
        }
        //内容 这里使用List<Map<String, Object>> 如果要用实体类就要转换或者改service 太麻烦
        //List<Map<String, String>> list = stateReportService.selectReportQuestion(reportId);
        List<List<Object>> total=new ArrayList<>();
        for(Map<String, Object> map : dataList){
            List<Object> info=new ArrayList<>();
            for (String param:params) {
                info.add(map.get(param));
            }
            total.add(info);
        }

        String fileName = URLEncoder.encode("巡检报告", "UTF-8").replaceAll("\\+", "%20");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");//设置响应头
        response.setHeader("mime","application/vnd.ms-excel");

        EasyExcel.write(response.getOutputStream())
                .head(heads)
                .sheet("巡检报告")
                .doWrite(total);

    }
}
